#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <unistd.h>
#include "Thread.hpp"

using namespace ThreadMoudle;

static const int gdefaultnum = 5;

template<typename T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void WakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool IsEmpty()
    {
        return _task_queue.empty();
    }
    void HanderTask(std::string& name) // this
    {
        while (true)
        {
            // 取任务
            LockQueue();
            while (IsEmpty() && _isrunning)
            {
                _sleep_thread_num++;
                Sleep();
                _sleep_thread_num--;
            }
            // 判定一种情况
            if (IsEmpty() && !_isrunning)
            {
                std::cout << name << "quit" << std::endl;
                UnlockQueue();
                break;
            }

            // 有任务
            T t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();

            t(); // 处理任务，此处不用/不能在临界区中处理
            std::cout << name << ":" << t.result() << std::endl;
        }
    }
public:
    ThreadPool(int thread_num = gdefaultnum) : _thread_num(thread_num), _isrunning(false), _sleep_thread_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    void Init()
    {
        func_t func = std::bind(&ThreadPool::HanderTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++)
        {
            std::string threadname = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(threadname, func);
        }
    }
    void Start()
    {
        _isrunning = true;
        for (auto& thread : _threads)
        {
            thread.Start();
        }
    }
    void Stop()
    {
        LockQueue();
        _isrunning = false;
        WakeupAll();
        UnlockQueue();
    }
    void Equeue(const T& in)
    {
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(in);
            if (_sleep_thread_num > 0)
            {
                Wakeup();
            }
        }
        UnlockQueue();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    int _thread_num;
    bool _isrunning;
    std::queue<T> _task_queue;
    std::vector<Thread> _threads;

    int _sleep_thread_num;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};